﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using System.Diagnostics;

namespace PublicClass.CadWatch
{
    /// <summary>
    /// Application 事件 – 对 AutoCAD 关闭、修改系统变量、开始双击以及进入和离开模式的状态等作出反应。对于系统变量的修改也有文档级事件。
    /// </summary>
    public class CadApplicationWatch
    {
        public CadApplicationWatch()
        {
            Application.SystemVariableChanged += appSysVarChanged;                  // 检测系统变量修改
            Application.PreTranslateMessage += PreTranslateMessageEvent;            // 处理cad中的win消息
        }

        ~CadApplicationWatch()
        {
            Application.SystemVariableChanged -= appSysVarChanged;
            Application.PreTranslateMessage -= PreTranslateMessageEvent;
        }

        private void appSysVarChanged(object senderObj, Autodesk.AutoCAD.ApplicationServices. SystemVariableChangedEventArgs sysVarChEvtArgs)
        {
            object oVal = Application.GetSystemVariable(sysVarChEvtArgs.Name);
            // 弹出消息框，显示系统变量的名称及新值
            CadUnits.CurEdit().WriteMessage(sysVarChEvtArgs.Name + " 系统变量改变." + "新值: " + oVal.ToString());
        }
        private void PreTranslateMessageEvent(object sender, PreTranslateMessageEventArgs e)
        {
            // e.Message.message
            // 样例：cad的键盘消息，提示输入输入的是哪个键
            if (e.Message.message == WinMsg.WM_KEYDOWN)
            {
                CadUnits.CurEdit().WriteMessage("\n处理cad中win消息,按键按下了:" + 
                    Convert.ToChar(e.Message.wParam.ToInt32()) + "\n");
            }
            else if (e.Message.message == WinMsg.WM_RBUTTONDOWN) // 右键按下消息
            {
                System.Windows.Forms.ContextMenuStrip menu = new System.Windows.Forms.ContextMenuStrip();
                menu.Items.Add("你好");
                menu.Items.Add("我是");
                menu.Items.Add("王阿非");
                menu.ItemClicked += EventHandler_RightMenuChick;
                menu.Show(e.Message.pt_x, e.Message.pt_y);
            }
            else if (e.Message.message == WinMsg.WM_LBUTTONDBLCLK)
            {
                // 双击
                CadUnits.WriteMessage("\n你双击了！！！");
            }
            // Debug.WriteLine("处理cad中win消息" + e.ToString());
        }
        // 右键菜单单击
        private void EventHandler_RightMenuChick(object sender, System.Windows.Forms.ToolStripItemClickedEventArgs e)
        {
            System.Windows.Forms.ContextMenuStrip strip = sender as System.Windows.Forms.ContextMenuStrip;
            System.Windows.Forms.MessageBox.Show(e.ClickedItem.Text);
        }
    }
}
